# -*- coding: utf-8 -*-
"""
商品图片下载
"""
import os
import time

from db.mysql import connect_db
from image.downloader import Downloader


"""
产品图片下载
"""
class Product:
    id:int = 0
    conn = None
    path = './file/image/product/'
    def __init__(self, id:int):
        self.conn = connect_db()
        self.id = id

    def download(self):
        if self.__set_rows():
            for row in self.rows:
                self.id = row[0]
                if 'http' in row[2]:
                    continue
                filename = row[3].split('/')[-1]
                if not os.path.exists(self.path + filename):
                    print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} downloading {self.id} - {filename} start')
                    Downloader.download(row[3],self.path,filename)
                    print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} downloading {self.id} - {filename} end')
                    time.sleep(5)
                self.__set_data(self.id, filename)
            return True
        else:
            return False

    def __set_rows(self):
        sql = "select * from t_product where id>%s order by id asc limit 10"
        cursor = self.conn.cursor()
        cursor.execute(sql, (self.id,))
        self.rows = cursor.fetchall()
        cursor.close()
        return True if self.rows else False

    def __set_data(self,id,filename):
        cursor = self.conn.cursor()
        cursor.execute(f'update t_product set thumb=\'{"/assets/img/product/"+filename}\' where id={id}')
        self.conn.commit()
        cursor.close()
        return True